﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using CeA.Reports.Atendimento.DataAccess.DTO;
using System.Security.Principal;
using CeA.Reports.Atendimento.DataAccess;
using CeA.Reports.Atendimento.DataAccess.DAO;
using Qtech.Reports.Atendimento.Services;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;

namespace CeA.Reports.Atendimento.Web {
    public class Global : System.Web.HttpApplication {

        protected void Application_Start(object sender, EventArgs e) {
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("pt-BR");
        }

        protected void Session_Start(object sender, EventArgs e) {

        }

        protected void Application_BeginRequest(object sender, EventArgs e) {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e) {
            if (Request.IsAuthenticated) {
                if (Application[User.Identity.Name] == null) {
                    //Determine this user's roles
                    List<RoleDTO> roles = CadastroFacade.GetUsuarioRoles(User.Identity.Name);

                    //Create an array of role names
                    string[] roleListArray = new string[roles.Count];
                    for (int i = 0; i < roles.Count; i++)
                        roleListArray[i] = roles[i].Nome;

                    GenericPrincipal principal = new GenericPrincipal(User.Identity, roleListArray);
                    
                    HttpContext.Current.User = principal;

                    Application.Add(User.Identity.Name, principal);
                }
                else {
                    HttpContext.Current.User = (GenericPrincipal)Application[User.Identity.Name];
                }
            }
        }

        protected void Application_Error(object sender, EventArgs e) {

        }

        protected void Session_End(object sender, EventArgs e) {
            Application.Remove(User.Identity.Name);
        }

        protected void Application_End(object sender, EventArgs e) {

        }
    }
}